import { createRouter, RouteRecordRaw, createWebHistory } from 'vue-router'
import SystemRouter from '@/router/module/system'
import MonitorRouter from '@/router/module/monitor'
import ArticleRouter from '@/router/module/article'
import 'vue-router'
import NProgress from 'nprogress'
import { getToken } from '@/utils/auth'

declare module 'vue-router' {
  interface RouteMeta {
    title: string
  }
}

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    component: () => import('../views/Login/index.vue')
  },
  {
    path: '/',
    component: () => import('@/components/Layout/Container.vue'),
    children: [
      {
        path: '/home',
        name: 'home',
        component: () => import('../views/Home/index.vue')
      },
      SystemRouter,
      MonitorRouter,
      ArticleRouter
    ]
  }
]

const router = createRouter({
  history: createWebHistory('/admin'),
  routes
})

NProgress.configure({ showSpinner: false })

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      next()
    }
  } else if (to.path === '/login') {
    next()
  } else {
    ElMessage.error("请重新登录")
    next(`/login?redirect=${to.fullPath}`)
  }
  NProgress.done()
})

router.afterEach(() => {
  NProgress.done()
})

export default router
